{% extends "base.html" %}

{% block content %}
<div class="max-w-7xl mx-auto">
    <div class="mb-6 flex items-center justify-between">
        <div>
            <button onclick="location.href='/documents'" class="text-indigo-600 hover:text-indigo-800 mb-2">
                <i class="fas fa-arrow-left mr-2"></i>Back to Documents
            </button>
            <h1 class="text-2xl font-bold text-gray-900" id="documentTitle">Document Viewer</h1>
        </div>
        <div class="flex space-x-3">
            <button onclick="editDocument()" class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700">
                <i class="fas fa-edit mr-2"></i>Edit
            </button>
            <button onclick="downloadDocument()" class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">
                <i class="fas fa-download mr-2"></i>Download
            </button>
        </div>
    </div>

    <div class="grid grid-cols-3 gap-6">
        <div class="col-span-2">
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <div id="documentViewer" class="min-h-screen">
                    <div class="flex items-center justify-center py-12">
                        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-span-1">
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 sticky top-6">
                <h2 class="text-lg font-semibold text-gray-900 mb-4">Document Information</h2>
                
                <div class="space-y-4">
                    <div>
                        <label class="text-sm font-medium text-gray-500">File Name</label>
                        <p class="text-gray-900" id="metaFileName">-</p>
                    </div>
                    
                    <div>
                        <label class="text-sm font-medium text-gray-500">Country/Region</label>
                        <p class="text-gray-900" id="metaCountry">-</p>
                    </div>
                    
                    <div>
                        <label class="text-sm font-medium text-gray-500">Document Type</label>
                        <p class="text-gray-900" id="metaType">-</p>
                    </div>
                    
                    <div>
                        <label class="text-sm font-medium text-gray-500">Regulation ID</label>
                        <p class="text-gray-900" id="metaRegId">-</p>
                    </div>
                    
                    <div>
                        <label class="text-sm font-medium text-gray-500">Issuing Authority</label>
                        <p class="text-gray-900" id="metaAuthority">-</p>
                    </div>
                    
                    <div>
                        <label class="text-sm font-medium text-gray-500">Effective Date</label>
                        <p class="text-gray-900" id="metaDate">-</p>
                    </div>
                    
                    <div>
                        <label class="text-sm font-medium text-gray-500">Version</label>
                        <p class="text-gray-900" id="metaVersion">-</p>
                    </div>
                    
                    <div>
                        <label class="text-sm font-medium text-gray-500">Status</label>
                        <p id="metaStatus">-</p>
                    </div>
                    
                    <div>
                        <label class="text-sm font-medium text-gray-500">Collection</label>
                        <p class="text-gray-900" id="metaCollection">-</p>
                    </div>
                    
                    <div>
                        <label class="text-sm font-medium text-gray-500">Tags</label>
                        <div id="metaTags" class="flex flex-wrap gap-2 mt-2"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
const docId = '{{ doc_id }}';
let currentDocument = null;

document.addEventListener('DOMContentLoaded', async () => {
    await loadDocument();
});

async function loadDocument() {
    try {
        const response = await fetch(`/api/documents/${docId}`);
        const data = await response.json();
        
        if (data.status === 'success') {
            currentDocument = data.document;
            displayMetadata(currentDocument);
            displayDocument(currentDocument);
        } else {
            showError('Failed to load document');
        }
    } catch (error) {
        console.error('Error loading document:', error);
        showError('Error loading document');
    }
}

function displayMetadata(doc) {
    document.getElementById('documentTitle').textContent = doc.file_name || doc.filename || 'Document';
    document.getElementById('metaFileName').textContent = doc.file_name || doc.filename || '-';
    document.getElementById('metaCountry').textContent = doc.country || '-';
    document.getElementById('metaType').textContent = (doc.document_type || doc.file_format || '-').toUpperCase();
    document.getElementById('metaRegId').textContent = doc.regulation_id || '-';
    document.getElementById('metaAuthority').textContent = doc.issuing_authority || '-';
    
    // Format date
    if (doc.effective_date) {
        try {
            let dateStr = doc.effective_date;
            if (typeof dateStr === 'string') {
                if (dateStr.includes('T')) {
                    dateStr = dateStr.split('T')[0];
                }
                document.getElementById('metaDate').textContent = dateStr.replace(/-/g, '/');
            } else {
                document.getElementById('metaDate').textContent = new Date(dateStr).toLocaleDateString();
            }
        } catch (e) {
            document.getElementById('metaDate').textContent = doc.effective_date;
        }
    } else {
        document.getElementById('metaDate').textContent = '-';
    }
    
    document.getElementById('metaVersion').textContent = doc.version || '-';
    document.getElementById('metaCollection').textContent = doc.collection || '-';
    
    // Status badge
    const statusColors = {
        'Draft': 'bg-yellow-100 text-yellow-800',
        'Effective': 'bg-green-100 text-green-800',
        'Expired': 'bg-red-100 text-red-800'
    };
    
    const status = doc.status || 'Unknown';
    const statusColor = statusColors[status] || 'bg-gray-100 text-gray-800';
    document.getElementById('metaStatus').innerHTML = `<span class="px-2 py-1 text-xs font-medium rounded-full ${statusColor}">${status}</span>`;
    
    // Tags
    const tagsContainer = document.getElementById('metaTags');
    tagsContainer.innerHTML = '';
    if (doc.tags && doc.tags.length > 0) {
        doc.tags.forEach(tag => {
            const tagEl = document.createElement('span');
            tagEl.className = 'px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full';
            tagEl.textContent = tag;
            tagsContainer.appendChild(tagEl);
        });
    } else {
        tagsContainer.innerHTML = '<span class="text-gray-400 text-sm">No tags</span>';
    }
}

function displayDocument(doc) {
    const viewer = document.getElementById('documentViewer');
    const fileFormat = doc.file_format || doc.document_type || '';
    
    if (fileFormat === 'pdf') {
        viewer.innerHTML = `<iframe src="/static/pdfs/${doc.filename}" class="w-full h-screen border-0 rounded-lg"></iframe>`;
    } else if (fileFormat === 'txt') {
        viewer.innerHTML = `<pre class="whitespace-pre-wrap text-gray-900 font-mono text-sm">${escapeHtml(doc.content_text || 'Content not available')}</pre>`;
    } else {
        viewer.innerHTML = `
            <div class="text-center py-12">
                <i class="fas fa-file text-gray-300 text-6xl mb-4"></i>
                <p class="text-gray-600">Preview not available for this file type</p>
                <p class="text-sm text-gray-500 mt-2">File type: ${fileFormat}</p>
                <button onclick="downloadDocument()" class="mt-4 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700">
                    <i class="fas fa-download mr-2"></i>Download File
                </button>
            </div>
        `;
    }
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function editDocument() {
    window.location.href = `/edit/${docId}`;
}

function downloadDocument() {
    if (currentDocument) {
        window.open(`/static/pdfs/${currentDocument.filename}`, '_blank');
    }
}

function showError(message) {
    const viewer = document.getElementById('documentViewer');
    viewer.innerHTML = `
        <div class="text-center py-12">
            <i class="fas fa-exclamation-triangle text-red-300 text-6xl mb-4"></i>
            <p class="text-red-600 font-medium">${message}</p>
            <button onclick="location.href='/documents'" class="mt-4 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">
                <i class="fas fa-arrow-left mr-2"></i>Back to Documents
            </button>
        </div>
    `;
}
</script>
{% endblock %}